package com.lnsf.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.lnsf.dao.IUser_DetailDao;
import com.lnsf.dbutils.DataAccess;
import com.lnsf.model.User_Detail;

public class User_DetailDaoImpl implements IUser_DetailDao {

	@Override
	public List<User_Detail> select() {
		List<User_Detail> list = new ArrayList<User_Detail>();
		Connection conn = null;
		PreparedStatement prep = null;
		ResultSet rs = null;
		try {
			conn = DataAccess.getConnection();
			prep = conn.prepareStatement("select * from user_detail");
			rs = prep.executeQuery();
			while (rs.next()) {
				User_Detail user_detail = new User_Detail(rs.getInt(1), rs.getString(2), rs.getString(3),
						rs.getString(4), rs.getString(5), rs.getString(6));
				list.add(user_detail);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DataAccess.closeConnection(rs, prep, conn);
		}
		return list;
	}

	@Override
	public int insert(User_Detail user_detail) {
		int flag = 0;
		Connection conn = null;
		PreparedStatement prep = null;
		try {
			conn = DataAccess.getConnection();
			prep = conn.prepareStatement("insert into user_detail values (?, ?, ?, ?,?,?)");
			prep.setInt(1, user_detail.getuId());
			prep.setString(2, user_detail.getuName());
			prep.setString(3, user_detail.getGender());
			prep.setString(4, user_detail.getTel());
			prep.setString(5, user_detail.getEmail());
			prep.setString(6, user_detail.getAddress());
			prep.execute();
			flag = 1;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DataAccess.closeConnection(prep, conn);
		}
		return flag;
	}

	@Override
	public int update(User_Detail user_detail) {
		int flag = 0;
		Connection conn = null;
		PreparedStatement prep = null;
		try {
			conn = DataAccess.getConnection();
			prep = conn.prepareStatement(
					"update user_detail set uName = ?,gender=?, tel=?,email=?,address=? where uId = ?");
			prep.setString(1, user_detail.getuName());
			prep.setString(2, user_detail.getGender());
			prep.setString(3, user_detail.getTel());
			prep.setString(4, user_detail.getEmail());
			prep.setString(5, user_detail.getAddress());
			prep.setInt(6, user_detail.getuId());
			prep.execute();
			flag = 1;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DataAccess.closeConnection(prep, conn);
		}
		return flag;
	}

	@Override
	public int delete(User_Detail user_detail) {
		int flag = 0;
		Connection conn = null;
		PreparedStatement prep = null;
		try {
			conn = DataAccess.getConnection();
			prep = conn.prepareStatement("delete from user_detail where uId = ?");
			prep.setInt(1, user_detail.getuId());
			prep.execute();
			flag = 1;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DataAccess.closeConnection(prep, conn);
		}
		return flag;
	}

}
